<template>
  <div class="HCFormFied field-box">
    <div class="attachment-box field-item upload-button">
      <div class="upload-button--box">
        <span class="label-require" v-if="isRequire && showRequire">*</span>
        <div class="upload-button__left">
          <el-upload class="upload-demo" :drag="drag" :class="{ 'drag-box': drag }" action="" :multiple="true"
            ref="upload" :auto-upload="false" :file-list="fileList" :on-change="uploadChange" :show-file-list="false"
            v-if="(!disabled) && (btnShowObj ? btnShowObj.upload : showUpload)" :accept="allowformatStr">
            <el-button v-if="!drag" type="primary" icon="el-icon-plus" class="button-new-tag" :loading="uploading">{{
              btnTitle }}<span v-if="this.maxnum">({{ fileList.length }}/{{ this.maxnum }})</span></el-button>
            <div class="drag-box-content" v-if="drag">
              <div class="file-list" v-if="drag && !isImage">
                <el-scrollbar class="scorll-Y" :style="{
                  height: fileList.length > 3 ? '100px' : fileList.length * itemHeight + 'px',
                }">
                  <el-tree class="filter-tree mt-5" :data="fileList" :props="{ label: 'name' }" node-key="unid"
                    default-expand-all :expand-on-click-node="false" :highlight-current="true"
                    :check-on-click-node="true" :show-checkbox="false" :check-strictly="false" :draggable="showUpload"
                    :allow-drop="attchmentCollapse" @node-drop="onDropOver" ref="tree3">
                    <span class="custom-tree-node" slot-scope="{ data }">
                      <div class="file-item">
                        <div>
                          <i class="el-icon-link" v-if="fileLinkShow"></i>
                          <el-tooltip popper-class="hc-dec-text" v-if="data.fileName.length > filenameLength"
                            :content="data.fileName" placement="top" effect="light">
                            <span class="filename" type="link" @click="handlePrevieFile(data)">{{
                              data.fileName.substring(0, filenameLength) + "..."
                            }}</span>
                          </el-tooltip>
                          <span v-else class="filename" type="link" :title="data.fileName"
                            @click="handlePrevieFile(data)">{{ data.fileName }}</span>
                        </div>
                        <div>
                          <span class="btn-down" v-if="!isShowMj" @click="handlePrevieFile(data)">预览</span>
                          <span class="btn-down" v-if="data.hasQy" @click="handleQyFile(data)">圈阅</span>
                          <span class="btn-down" v-if="showEditButton(data)" @click="handleEditFile(data)">编辑</span>
                          <span class="btn-down"
                            v-if="(btnShowObj ? btnShowObj.bownload : !hiddenDownload) && (data.fileType && data.fileType != 'url')"
                            @click="handleDownload(data)">{{ isShowMj ? "查看" : "下载" }}</span>
                          <span class="btn-remove" v-if="btnShowObj ? btnShowObj.bownload : showDelete"
                            @click="handleRemove(data, btnTitle)">删除</span>
                          <span style="margin-left:5px" v-if="isShowMj">{{ showMjText || mj }}</span>
                        </div>
                      </div>
                    </span>
                  </el-tree>
                </el-scrollbar>
              </div>
              <div class="el-upload__text"><i class="el-icon-plus"></i>将文件拖到此处，或<em>点击上传</em></div>
            </div>
          </el-upload>
          <el-button v-if="isAddYJW && showUpload" style="margin-left:10px" type="primary" icon="el-icon-plus"
            class="button-new-tag" @click="handleAddYJW">添加依据文</el-button>
        </div>
      </div>
      <div class="file-list" v-if="isImage">
        <el-scrollbar class="scorll-Y" :style="{
          height: fileList.length > 0 ? '150px' : fileList.length * 150 + 'px',
        }">
          <div style="display: flex;">
            <div class="file-item" v-for="(item, index) in fileList" :key="index">
              <div style="display: flex;flex-direction: column;">
                <div v-if="fileTypeByName(item.fileName, 'img')">
                  <el-image class="image-list" :src="item.url" :preview-src-list="[item.url]">
                  </el-image>
                </div>
                <div>
                  <span class="btn-down" v-if="!isShowMj" @click="handlePrevieFile(data)">预览</span>
                  <span class="btn-down" v-if="item.hasQy" @click="handleQyFile(item)">圈阅</span>
                  <span class="btn-down" v-if="showEditButton(item)" @click="handleEditFile(item)">编辑</span>
                  <span class="btn-down"
                    v-if="(btnShowObj ? btnShowObj.bownload : !hiddenDownload) && (item.fileType && item.fileType != 'url')"
                    @click="handleDownload(data)">{{ isShowMj ? "查看" : "下载" }}</span>
                  <span class="btn-remove" v-if="btnShowObj ? btnShowObj.bownload : showDelete"
                    @click="handleRemove(data, btnTitle)">删除</span>
                </div>
              </div>
            </div>
          </div>

        </el-scrollbar>
      </div>
      <div class="file-list" v-if="(disabled || !drag) && !isImage">
        <el-scrollbar class="scorll-Y" :style="{
          height: fileList.length > 6 ? '200px' : fileList.length * itemHeight + 'px',
        }">
          <el-tree class="filter-tree mt-5" :data="fileList" :props="{ label: 'name' }" node-key="unid"
            default-expand-all :expand-on-click-node="false" :highlight-current="true" :check-on-click-node="true"
            :show-checkbox="false" :check-strictly="false" :draggable="showUpload" :allow-drop="attchmentCollapse"
            @node-drop="onDropOver" ref="tree3">
            <span class="custom-tree-node" slot-scope="{ data }">
              <div v-if="data.isShow">
                <div class="file-item">
                  <div style="display: flex;">
                    <i class="el-icon-link" v-if="fileLinkShow"></i>
                    <div v-else>
                      <div v-if="fileTypeByName(data.fileName, 'img')">
                        <el-image style="width: 20px; height: 20px" :src="data.url" :preview-src-list="[data.url]">
                        </el-image>
                      </div>
                      <div v-else-if="isVideoFile(data.fileName)">
                        <el-image style="width: 20px; height: 20px" :src="videoCover">
                        </el-image>
                      </div>
                      <div v-else>
                        <el-image class="file-icon" :src="fileTypeByFileName(data)">
                          <img slot="error" class="file-icon" src="/fileicon/UNKNOWN.png" alt="未知文件">
                        </el-image>
                      </div>
                    </div>
                    <span v-if="showFilexh">{{ data.xh }}、</span>
                    <el-tooltip popper-class="hc-dec-text" v-if="data.fileName.length > filenameLength"
                      :content="data.fileName" placement="top" effect="light">
                      <span class="filename" type="link" @click="handlePrevieFile(data)">{{
                        data.fileName.substring(0, filenameLength) + "..."
                      }}</span>
                    </el-tooltip>
                    <span v-else class="filename" type="link" :title="data.fileName" @click="handlePrevieFile(data)">{{
                      data.fileName }}</span>
                  </div>
                  <div>
                    <span class="btn-down" v-if="showPreview(data.fileType) && !isShowMj"
                      @click="handlePrevieFile(data)"><i class="el-icon-view file-btn-icon"></i>预览</span>
                    <span class="btn-down" v-if="data.hasQy" @click="handleQyFile(data)"><i
                        class="el-icon-view file-btn-icon"></i>圈阅</span>
                    <span class="btn-down" v-if="showEditButton(data)" @click="handleEditFile(data)"><i
                        class="el-icon-edit file-btn-icon"></i>编辑</span>
                    <span class="btn-down"
                      v-if="(btnShowObj ? btnShowObj.bownload : !hiddenDownload) && (data.fileType && data.fileType != 'url')"
                      @click="handleDownload(data)"><i class="el-icon-download file-btn-icon"></i>{{ isShowMj ? "查看" :
                        "下载" }}</span>
                    <span class="btn-remove" v-if="btnShowObj ? btnShowObj.delete : showDelete"
                      @click="handleRemove(data, btnTitle)"><i class="el-icon-delete file-btn-icon"></i>删除</span>
                    <span style="margin-left:5px" v-if="isShowMj">
                      <el-select class="hc-select" style="width:120px" size="mini" :clearable="true"
                        :disabled="type == 'zw' || !showUpload" v-model="data.mj"
                        @change="(e) => onChangeFjMj(e, data)">
                        <el-option v-for="(item, index) in showMjOptionList" :disabled="item.disabled" :key="index"
                          :label="item" :value="item">
                        </el-option>
                      </el-select>
                    </span>
                  </div>
                </div>
                <div v-if="isshowcreate" class="file-create-info hc-min-text" style="color:#999;"><span
                    style="margin-rigth:10px" v-if="data.createName">上传人：{{ data.createName }}</span><span
                    v-if="data.createTime">上传时间：{{ data.createTime }}</span></div>
              </div>
            </span>
          </el-tree>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>
<script>
import
{
  openUpload,
  getOpenList,
  delAttachment,
  getOpenDownloadUrl,
  getOpenDownloadFile,
  attachmentRank,
  saveAttachment
} from "../api/common/attachment";
import request from '@/utils/request'
import filePreview, { fileQyPreview, formatFileUrl, getFileTypeByFileName } from "../utils/filePreview";
import { getList } from "../api/common/wordfiles";
import { mapMutations, mapActions, mapGetters } from "vuex";
// import { delWcgl } from "@/api/module/wcgl/wcgl";
import showDocumentPaperModel from "./DocumentPaperModel/index";
import { saveAttachmentApi } from "../api/common/gwfj";
import { isVideoFile } from "../utils";
export default {
  name: "AttachmentView",
  props: [
    "showUpload", //是否显示上传按钮
    "title", //上传按钮标题
    "relationUnid", //文件关联数据unid
    "moduleName", //模块名
    "formType",//表单类型
    "hiddenDownload",//是否隐藏下载
    "type", //类型
    "showZw", //是否是正文
    "showDelete", //是否显示删除按钮
    "currentPerson", //是否是当前办理人
    "allowformat", //允许文件上传类型
    "nochangebt", //是否不改变表单标题
    "disabled", //状态
    "maxnum",  //允许上传的最大附件数目
    "drag", //是否支持拖拽上传
    "isRequire",//是否必填
    "isImage",//是否显示图片大图
    "isshowcreate",//是否显示创建信息
    "btnShowObj",//按钮显示(针对每个附件控件)
    "isAddYJW",// 是否能添加依据文
    "mj"//密级
  ],
  data()
  {
    return {
      // drag:false,
      // isImage:false,
      allowformatStr: "",
      showRequire: window.HC_config.VUE_APP_SHOWREQUIRE || false,
      uploading: false, //显示loading
      fileList: [], //文件列表
      //文件标题显示长度
      filenameLength: window.HC_config.VUE_SHOW_FILENAME_LENGTH || 6,
      //是否wps编辑文件
      isWpsEdit: window.HC_config.VUE_APP_WPS_EDIT_FJ || false,
      // 是否显示文件序号
      showFilexh: window.HC_config.VUE_APP_SHOW_FILEXH || false,
      // 保密警示语
      bmWarningTips: window.HC_config.VUE_APP_BMJSY || '',
      //是否显示密级
      isShowMj: window.HC_config.VUE_APP_FJSHOWMJ || false,
      // 上传时wps文件改成office文件
      fileWpsToOffice: window.HC_config.VUE_APP_UPLOAD_WPS_TO_OFFICE || false,
      dialogVisible: false,
      uploadFileList: [],
      //签名url
      signImage: null,
      fileLinkShow: '',
      fileType: [
        {
          img: '',
          typeName: ['doc', 'docx', 'ref', 'TXT'],
          type: 'text'
        },
        {
          img: '',
          typeName: ['PDF', 'PPT', 'PPTX'],
          type: 'file'
        },
        {
          img: '',
          typeName: ['JPG', 'PNG', 'JPEG'],
          type: 'img'
        },
        {
          img: '',
          typeName: ['XLS', 'XLSX'],
          type: 'excal'
        }
      ],
      videoCover: "",
      //最大长度
      maxLength: 0,
      //显示密级文本
      showMjText: null,
      //密级顺序
      mjRank: {
        "非密": 0,
        "内部": 1,
        "秘密": 2,
        "机密": 3,
        "绝密": 4
      }
    };
  },
  computed: {
    ...mapGetters(['userInfo']),
    btnTitle()
    {
      if (this.title)
      {
        return this.title;
      }
      if (this.showZw)
      {
        return "上传正文";
      }
      if (this.type == 'cld')
      {
        return "上传处理单";
      }
      return "上传附件";
    },
    itemHeight()
    {
      if (this.isshowcreate)
      {
        return 65;
      }
      else
      {
        return 35;
      }
    },
    //是否有圈阅功能
    hasQuanyue()
    {
      const moduleList = window.HC_config.VUE_APP_QUAN_YUE || [];
      if (!Array.isArray(moduleList))
      {
        return false;
      }
      return moduleList.includes(this.moduleName);
    },
    //密级可选
    showMjOptionList()
    {
      let valueToReturn = ["非密"];
      if (this.showMjText)
      {
        if (this.showMjText == "内部")
        {
          valueToReturn = ["内部", "非密"];
        }
        else if (this.showMjText == "秘密")
        {
          valueToReturn = ["秘密", "内部", "非密"];
        }
        else if (this.showMjText == "机密")
        {
          valueToReturn = ["机密", "秘密", "内部", "非密"];
        }
        else if (this.showMjText == "绝密")
        {
          valueToReturn = ["绝密", "机密", "秘密", "内部", "非密"];
        }
      }
      return valueToReturn;
    }
  },
  watch: {
    relationUnid(newV, oldV)
    {
      this.getAttachList();
    },
    showMjText(newV, oldV)
    {
      if (this.isShowMj)
      {
        this.fileList.forEach(pre_file =>
        {
          if (pre_file.type == 'zw')
          {
            pre_file.mj = newV;
          }
          else
          {
            pre_file.mj = null;
          }
          //根据密级控制是否显示
          pre_file.isShow = true;
        })
        if (this.fileList.length > 0)
        {
          this.$set(this.fileList, 0, this.fileList[0]);
        }
      }
    }
  },
  created()
  {
    if (this.allowformat)
    {
      let formatList = this.allowformat.split(",");
      formatList = formatList.map(per_item => "." + per_item);
      this.allowformatStr = formatList.join(",");
    }
    this.fileLinkShow = this.$store.state.settings.fileLinkShow
    // 查询文件列表
    this.getAttachList();
    this.showMjText = this.mj;
  },
  methods: {
    ...mapMutations("uploadLog", ["addLog"]),
    ...mapActions("uploadLog", ["staruploadAsync"]),
    //是否显示编辑按钮
    showEditButton(P_File)
    {
      if (this.isWpsEdit)
      {
        const fileType = getFileTypeByFileName(P_File.fileName);
        return ['doc', 'docx'].includes(fileType);
      }
      return false;
    },
    //是否显示圈阅按钮
    showQuanyueButton(P_FileName)
    {
      const fileType = getFileTypeByFileName(P_FileName);
      return ['doc', 'docx', 'pdf'].includes(fileType);
    },
    // 判断是否显示预览按钮
    showPreview(fileType)
    {
      if (fileType == 'zip' || fileType == 'rar' || fileType == 'mp3' || fileType == 'mp4' || fileType == 'mov')
      {
        return false
      }
      else
      {
        return true
      }
    },
    fileTypeByName(P_Name, P_Type)
    {
      let sname = P_Name.slice(P_Name.lastIndexOf('.') + 1)
      for (var num = 0; num < this.fileType.length; num++)
      {
        if (this.fileType[num].typeName.some(item => item.toUpperCase() == sname.toUpperCase()) && P_Type == this.fileType[num].type)
        {
          return true
        }
      }
      return false
    },
    fileTypeByFileName(P_Data)
    {
      let sname = ''
      if (P_Data.fileType == 'url')
      {
        sname = 'HTML'
      }
      else
      {
        sname = P_Data.fileName.slice(P_Data.fileName.lastIndexOf('.') + 1)
      }
      // let sname = P_Name.slice(P_Name.lastIndexOf('.') + 1)
      return `/fileicon/${sname.toUpperCase()}.png`
    },
    // 查询文件列表
    getAttachList()
    {
      if (this.showZw && this.type == "gwcs")
      {
        //公文传输 需要查询wordFFileList
        this.getWordFileList();
      }
      else
      {
        this.getAttachFileList();
      }
    },
    //提供给外部获取文件列表
    getFileList()
    {
      return this.fileList;
    },
    //监听文件拖动
    attchmentCollapse(moveNode, inNode, type)
    {
      if (type === "inner")
      {
        return false;
      }
      return true;
    },
    onDropOver()
    {
      this.fileList.forEach((pre_item, index) =>
      {
        pre_item.xh = index;
      })
      attachmentRank(this.fileList).then(res =>
      {
        // this.getAttachList();
      })
    },
    //上传确认提示框
    uploadConfirm()
    {
      return new Promise((resolve, reject) =>
      {
        var message = `<span style="color: red;">${this.bmWarningTips}</span>`
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then((res) =>
        {
          resolve(true);
        }).catch((e) =>
        {
          this.$message({
            type: 'warning',
            message: '取消文件上传'
          });
          reject("取消上传")
        });
      })
    },
    //文件上传前钩子
    async beforeUpload(file)
    {
      if (this.maxnum)
      {
        if (this.fileList.length == this.maxnum || this.fileList.length > this.maxnum)
        {
          this.$message.error('文件上传数量不允许大于上传的最大数量');
          return false;
        }
      }
      let tempArr = file.name.split(".");
      let fileType = tempArr[tempArr.length - 1];
      if (this.allowformat)
      {
        if (this.allowformat.indexOf(fileType) < 0)
        {
          this.$message.error("不允许上传此格式");
          return false;
        }
      }
      // const isLt100M = file.size / 1024 / 1024 < 100
      // if (!isLt100M) {
      //   this.$message.error('文件不能大于 100MB!')
      //   return false
      // }
      //确认提示框
      if (this.bmWarningTips)
      {
        return await this.uploadConfirm();
      }

      //  手动上传
      return true;
    },
    uploadFile(file, fields)
    {
      //调用上传之前修改文件状态，避免重复上传
      file.status = "done";
      let uploadFile = file.file || file.raw;
      if (this.fileWpsToOffice)
      {
        const splits = uploadFile.name.split(".");
        const name = splits[0];
        const suffix = (splits[1] || "").toLowerCase();
        if (suffix && ['wps', 'et'].includes(suffix))
        {
          const fileSuffix = suffix == 'wps' ? "docx" : "xlsx";
          let f = new File([uploadFile], `${name}.${fileSuffix}`);
          f.uid = uploadFile.uid; // new File 没有uid属性，会导致组件底层报错，这里手动加上
          uploadFile = f;
        }
      }

      const formData = new FormData();
      formData.append("file", uploadFile);
      formData.append("relationUnid", this.relationUnid);
      formData.append("moduleName", this.moduleName);
      let type = this.showZw ? "zw" : "1";
      type = this.type ? this.type : type;
      if (type == "zw")
      {
        formData.append("mj", this.showMjText);
      }
      // if (this.title) type = this.moduleName;
      formData.append("type", type);
      const chunkSize = 1024 * 1024;
      if (uploadFile.size < (chunkSize * 10))
      {
        this.uploading = true;
        openUpload(formData, (progress) =>
        {
          this.$emit("AttachmentViewProgressUpdate", progress);
        })
          .then((res) =>
          {
            this.$emit("getSuccessInfo", res.result);
            this.uploading = false;
            //附件上传成功回调，给控件化使用
            this.$emit("UploadSuccessHandle", res.result, this.nochangebt);
            //  设置图片
            const item = res.result;
            item.uid = item.unid;
            item.status = "done";
            item.url = getOpenDownloadUrl(item.unid);
            item.name = item.fileName;
            item.xh = item.xh + 1;
            item.hasQy = false;
            item.isShow = true;
            if (this.hasQuanyue)
            {
              item.hasQy = this.showQuanyueButton(item.fileName);
            }
            if (this.isVideoFile(item.fileName))
            {
              this.getVideoCover(item)
            }
            if (this.showZw)
            {
              this.fileList.push(item);
              this.$emit("zwList", this.fileList);
            } else
            {
              this.fileList.push(item);
            }
            this.$emit("fileUploadSuccess", res.result);
          })
      }
      else
      {
        let hash = new Date().getTime() + "" + Math.floor(Math.random() * 1000);
        const totalChunks = Math.ceil(uploadFile.size / chunkSize);
        let chunk = 0;
        let params = {
          type: type,
          relationUnid: this.relationUnid,
          moduleName: this.moduleName
        }
        //添加上传记录
        let uploadLogItem = {
          url: "/attachment/api/uploadChunk",//上传地址
          params: JSON.parse(JSON.stringify(params)),//上传参数
          fileName: uploadFile.name,//文件名称
          fileSize: uploadFile.size,//文件大小
          progress: 0,//进度
          totalChunks: totalChunks,// 总片数
          chunk: chunk,//已上传片数
          state: 0,// 状态 0 正在上传 1 暂停 2 上传完毕
          file: uploadFile, //文件本地 持久化时会舍弃
          hash: hash,//上传记录唯一id
        }
        this.addLog(uploadLogItem);//添加记录
        //开始上传
        this.staruploadAsync(hash).then(res =>
        {
          this.$emit("getSuccessInfo", res.result);
          this.uploading = false;
          //附件上传成功回调，给控件化使用
          this.$emit("UploadSuccessHandle", res.result, this.nochangebt);
          //  设置图片
          const item = res.result;
          item.uid = item.unid;
          item.status = "done";
          item.url = getOpenDownloadUrl(item.unid);
          item.name = item.fileName;
          item.xh = item.xh + 1;
          item.hasQy = false;
          item.isShow = true;
          if (this.hasQuanyue)
          {
            item.hasQy = this.showQuanyueButton(item.fileName);
          }
          if (this.isVideoFile(item.fileName))
          {
            this.getVideoCover(item)
          }
          if (this.showZw)
          {
            this.fileList.push(item);
            this.$emit("zwList", this.fileList);
          }
          else
          {
            this.fileList.push(item);
          }
          this.$emit("fileUploadSuccess", res.result);
        })
          .catch(err =>
          {
            this.uploading = false;
          });
      }
    },
    isVideoFile(fileName)
    {
      var suffix = `(swf|flv|mp4|rmvb|avi|mpeg|ra|ram|mov|wmv)`;
      var regular = new RegExp(`.*\.${suffix}`);
      return regular.test(fileName);
    },
    // 获取视频第一帧为封面
    getVideoCover(P_File)
    {
      const video = document.createElement('video')
      video.src = P_File.url
      let canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      video.crossOrigin = 'anonymous';  // 解决跨域问题，也就是提示污染源资源无法转换视频
      video.currentTime = 1;  // 第一帧
      video.oncanplay = () =>
      {
        canvas.width = video.clientWidth ? video.clientWidth : 320;
        canvas.height = video.clientHeight ? video.clientHeight : 320;
        // 利用canvas对象方法绘图
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
        // 转换成base64形式
        let videoFirstimg = canvas.toDataURL("image/png");
        this.videoCover = videoFirstimg
        video.remove()
        canvas.remove()
      }
    },
    //上传处理函数
    async uploadChangeHandler(P_File, P_FileList) 
    {
      console.log("上传处理函数", P_FileList.length);
      // 验证文件数量
      if (this.maxnum && P_FileList.length > this.maxnum) 
      {
        this.$message.error(`文件上传数量不能超过最大数量：${this.maxnum}`);
        //手动上传需要移除
        this.$refs.upload.handleRemove(P_File);
        return;
      }

      // 验证文件格式
      const validateFileFormat = (P_TeamFile) =>
      {
        const fileType = P_TeamFile.name.split('.').pop().toLowerCase();
        return this.allowformat && !this.allowformat.includes(fileType);
      };

      const invalidFiles = P_FileList.filter((Pre_TeamFile) => Pre_TeamFile.status === 'ready' && validateFileFormat(Pre_TeamFile));

      if (invalidFiles.length > 0)
      {
        const invalidFileTypes = invalidFiles
          .map((file) => file.name.split('.').pop().toLowerCase())
          .join(', ');
        this.$message.error(`以下文件格式不被允许：${invalidFileTypes}`);
        invalidFiles.forEach((Pre_TeamFile) => 
        {
          // 手动上传需要移除
          this.$refs.upload.handleRemove(Pre_TeamFile);
        });
        return;
      }

      try
      {
        // 显示确认提示框（如果配置了）
        if (this.bmWarningTips) 
        {
          await this.uploadConfirm(this.bmWarningTips);
        }

        P_FileList.forEach(pre_file =>
        {
          if (pre_file.status === 'ready')
          {
            // 提交文件
            this.uploadFile(pre_file);
          }
        });

        //this.$refs.upload.submit();
      }
      catch (error) 
      {
        //手动上传需要移除
        this.$refs.upload.handleRemove(P_File);
        console.error("上传失败", error);
      }
    },
    // 文件状态改变
    uploadChange(file, fileList)
    {
      if (file.status == 'ready')
      {
        let len = fileList.length;
        this.maxLength = Math.max(len, this.maxLength)
        console.log("len", len, "maxLength", this.maxLength);
        setTimeout(() =>
        {
          if (this.maxLength == len)
          {
            this.maxLength = 0;
            this.uploadChangeHandler(file, fileList);
          }
        }, 500)
      }
    },
    //文件删除
    handleRemove(file, btnTitle)
    {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() =>
        {
          delAttachment({ unids: file.unid })
            .then((res) =>
            {
              this.$message.success('删除成功');
              const index = this.fileList.indexOf(file);
              const newFileList = this.fileList.slice();
              newFileList.splice(index, 1);
              this.fileList = newFileList;
              this.$emit("zwList", this.fileList);
            })
            .catch((err) =>
            {
              console.log(err);
            });
        })
    },
    //文件下载
    handleDownload(file)
    {
      // window.open(getOpenDownloadUrl(file.unid));

      let requestParams = {
        url: getOpenDownloadUrl(file.unid),
        method: "get",
        responseType: 'blob'
      };

      let fileName = file.fileName;
      //执行请求
      request(requestParams)
        .then((res) =>
        {
          if (res instanceof Blob)
          {
            this.download(res, fileName);
          }
          else if (res.data instanceof Blob)
          {
            this.download(res.data, fileName);
          }
        })
    },
    download(data, fileName)
    {
      if (!data)
      {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    //是否是xls
    isExcelFile(file)
    {
      if (file.fileName.indexOf(".xls") != -1)
      {
        return true;
      }
      return false;
    },
    //在线预览文件
    handlePrevieFile(file)
    {
      filePreview(file, (this.btnShowObj ? this.btnShowObj.bownload : !this.hiddenDownload), this.formType, this.moduleName);
    },
    //获取wordKList文件
    getWordFileList()
    {
      if (
        this.relationUnid === "" ||
        typeof this.relationUnid === "undefined" ||
        this.moduleName === ""
      )
      {
        this.fileList = [];
        return;
      }
      const params = {
        parentUnid: this.relationUnid,
      };
      getList(params).then((res) =>
      {
        if (res.code == 200)
        {
          this.fileList = [];
          res.result.data.map((item, index) =>
          {
            var file = {};
            (file.fileName = item.attachName),
              (file.status = "done"),
              (file.unid = item.unid);
            (file.xh = index + 1);
            file.url = item.url;
            this.fileList.push(file);
          });
          if (this.hasQuanyue)
          {
            this.getAttachQuanyueFileList();
          }
        }
      });
    },
    //获取附件
    getAttachFileList()
    {
      if (
        this.relationUnid === "" ||
        typeof this.relationUnid === "undefined" ||
        this.moduleName === ""
      )
      {
        this.fileList = [];
        return;
      }
      const params = {
        relationUnid: this.relationUnid,
        moduleName: this.moduleName,
        type: this.showZw ? "zw" : this.type ? this.type : "1",
        pageNum: 1,
        pageSize: 100,
      };
      getOpenList(params)
        .then((res) =>
        {
          this.fileList = [];
          if (res.code === 200)
          {
            const list = [];
            let lastItem;
            res.result.data.map((item, index) =>
            {
              if (!lastItem)
              {
                lastItem = item;
              }
              if (lastItem.createTime < item.createTime)
              {
                lastItem = item;
              }
              item.uid = item.unid;
              item.status = "done";
              item.url = getOpenDownloadUrl(item.unid);
              item.name = item.fileName;
              item.xh = index + 1;
              item.hasQy = false;
              if (this.hasQuanyue)
              {
                item.hasQy = this.showQuanyueButton(item.fileName);
              }
              //根据密级控制是否显示
              if (item.mj && this.isShowMj)
              {
                //获取密级排名
                let rankNum = this.mjRank[item.mj];
                if (rankNum && rankNum > 0)
                {
                  //用户密级
                  let userMj = this.userInfo.mj;
                  if (userMj)
                  {
                    let userRankNum = this.mjRank[userMj];
                    if (userRankNum >= rankNum)
                    {
                      item.isShow = true;
                    }
                    else
                    {
                      item.isShow = false;
                    }
                  }
                  else
                  {
                    item.isShow = false;
                  }
                }
                else
                {
                  item.isShow = true;
                }
              }
              else
              {
                item.isShow = true;
              }

              list.push(item);
              if (this.isVideoFile(item.fileName))
              {
                this.getVideoCover(item)
              }
            });
            if (this.showZw)
            {
              this.fileList = list;
              this.$emit("zwList", this.fileList);
            } else
            {
              this.fileList = list;
            }
            this.$emit("getFilelist", this.fileList)
            if (this.hasQuanyue)
            {
              this.getAttachQuanyueFileList();
            }
          } else if (
            res.message ==
            "filename : [chrome.exe], extension : [exe], allowed extension : [[bmp, gif, jpg, jpeg, png, doc, docx, xls, xlsx, ppt, pptx, html, htm, txt, rar, zip, gz, bz2, pdf]]"
          )
          {
            this.$message.error("文件格式不受支持，请更换");
          } else
          {
            this.$message.error("上传失败,请重试！");
          }
        })
        .catch((err) =>
        {
          console.log(err);
        });
    },
    //获取附件圈阅文件
    getAttachQuanyueFileList()
    {
      if (!this.relationUnid || !this.moduleName)
      {
        return;
      }
      const params = {
        relationUnid: this.relationUnid,
        moduleName: this.moduleName + "_wordQY",
        pageNum: 1,
        pageSize: 100,
      };
      getOpenList(params)
        .then((res) =>
        {
          if (res.code === 200)
          {
            let list = res.result.data;
            this.fileList.forEach(item => 
            {
              list.forEach(qyItem => 
              {
                if (item.unid == qyItem.type)
                {
                  item.hasQy = true;
                }
              })
            })
          }
        })
        .catch((err) =>
        {
          console.log(err);
        });
    },
    //查看圈阅
    handleQyFile(P_File)
    {

      fileQyPreview({
        file: formatFileUrl(P_File, this.moduleName),
        unid: this.relationUnid,
        fileUnid: P_File.unid,
        fileName: P_File.fileName,
        formType: this.formType,
        moduleName: this.moduleName,
      })
    },
    //更新密级
    updateMj(P_Mj)
    {
      this.showMjText = P_Mj;
    },
    /**
     * 添加依据文
     */
    handleAddYJW()
    {
      showDocumentPaperModel().then(res =>
      {
        res.choiceData.forEach((item) =>
        {
          let type = "依据文";
          if (item.yjwModuleName == "swgl")
          {
            type = "收文";
          }
          else if (item.yjwModuleName == "fwgl")
          {
            type = "发文";
          }
          else if (item.yjwModuleName == "qbgl")
          {
            type = window.HC_config.VUE_APP_QBGLNAME || "签报";
          }
          else if (item.yjwModuleName == "grzl")
          {
            type = "资料";
          }
          else if (item.yjwModuleName == "cyjgl")
          {
            type = "阅件";
          }

          let params = {
            bt: item.bt,
            ssgwUnid: this.relationUnid,
            moduleName: this.moduleName,
            type: type,
            yjwModuleUnid: item.unid,
            yjwModuleName: item.yjwModuleName
          };
          saveAttachmentApi(params).then((res) =>
          {
            //刷新表单中的依据文组件数据
            this.$bus.$emit('reloadAttachment')
          });
        });
      })
    },
    /**
     * 编辑文件
     * @param { Object } P_File
     */
    handleEditFile(P_File)
    {
      let VUE_APP_BASE_API = localStorage.getItem("local_server_ip") || window.HC_config.VUE_APP_BASE_API || process.env.VUE_APP_BASE_API;
      editGwDocFj(
        VUE_APP_BASE_API,
        P_File.unid,
        this.moduleName,
        this.userInfo.personCommonname,
      );
    },
    /**
     * 监听附件密级修改
     */
    onChangeFjMj(P_Mj, P_File)
    {
      let file = { unid: P_File.unid, mj: P_Mj };
      saveAttachment(file).then(res =>
      {
        P_File.mj = P_Mj;
      })
    }
  },
};
</script>
<style lang="scss" scoped>
.image-list {
  width: 100px;
  height: 100px;
}

.file-icon {
  width: 20px;
  height: 20px;
  margin-right: 5px;
}

.upload-button {
  display: flex;
  flex-direction: column;
  align-items: flex-start !important;
  justify-content: center;
}

.attachment-box {
  width: 100%;
  height: 100%;
  padding-left: 10px;

  // padding: 0 10px;
  ::v-deep .el-upload-dragger {
    width: 100%;
    height: 150px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .el-icon-plus {
    font-size: 16px;
    margin: 10px auto;
    border: 2px solid #333;
    padding: 4px;
    border-radius: 4px;
  }

  .file-box {
    width: 100%;
  }

  .upload-demo {
    display: inline-block;
    // justify-content: center;
  }
}

.filename {
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin-right: 15px;
}

.file-list {
  display: flex;
  flex-direction: column;

  .file-item {
    width: 100%;
    line-height: 1.5em;
    margin-right: 10px;
    // justify-content: space-between;
    align-items: center;
    display: flex;
    font-size: 16px;
    color: #409eff;
    margin-top: 5px;

    .el-icon-link {
      font-size: 18px;
      margin-right: 5px;
      transform: translateY(2px);
    }

    .btn-down {
      color: #409eff;
      cursor: pointer;
      margin-left: 10px;
    }

    .btn-remove {
      color: #f56c6c;
      cursor: pointer;
      margin-left: 10px;
    }

    .file-btn-icon {
      font-size: 18px;
      vertical-align: middle;
    }
  }
}

.scorll-Y ::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
}

.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.upload ::v-deep .el-upload,
.upload ::v-deep .el-upload-dragger {
  width: 100%;
  height: auto;
}

.drag-box {
  width: 100%;

  ::v-deep .el-upload {
    width: 100%;
  }
}

::v-deep .el-icon-caret-right {
  width: 0;
  padding: 0;
}

.drag-box-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

::v-deep .el-tree-node__content {
  height: auto;
}

.file-create-info {
  line-height: 1.2em;
}

.upload-button--box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .field-item--left {
    display: flex;
    align-items: center;
  }

  .field-item--right {
    display: flex;
    align-items: center;
  }
}

.upload-button__left {
  width: 100%;
}
</style>
